import SwiftUI

struct FoodsListModel: Codable {
    let total: Int
    let rows: [FoodItemRespModel]
}

struct FoodListView: View {
    
    var storeId: Int
    
    @State private var foods: [FoodItemModel] = []
    
    @Environment(Router.self) private var router
    @Environment(PopupModel.self) private var popup
    @Environment(IndicatorModel.self) private var indicator: IndicatorModel
    
    var body: some View {
        LazyVStack(spacing: 12.0) {
            ForEach(foods) { food in
                FoodItemHStackView(model: food)
            }
        }
        .task {
            await getStoreFoods()
        }
    }
    
    private func getStoreFoods() async {
        indicator.show(content: .loading)
        do {
            let target = API.foodList(storeId: storeId, pageSize: 9999, pageNum: 1)
            let foodListRespModel = try await NetworkManager.shared.request(target, responseType: FoodsListModel.self)
            foods = foodListRespModel.rows.map({ FoodItemModel(respModel: $0) })
            indicator.hide()
        } catch {
            if let error = error as? BaseError {
                popup.show(content: error.message)
            }
            indicator.hide()
        }
    }

}

#Preview {
    FoodListView(storeId: 0)
}
